package com.ysh.webflux.service.impl;

import com.ysh.webflux.pojo.User;
import com.ysh.webflux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.data.relational.core.query.Update;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 袁胜虎 on 2022/9/22 21:22
 */
@Service
public class UserServiceImpl implements UserService {
    //模板对象,操作数据库用的
    private R2dbcEntityTemplate r2dbcEntityTemplate;

    @Autowired
    public void setR2dbcEntityTemplate(R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    @Override
    public Mono<User> findById(Long id) {
        //select * from xxx where uid =xxx
        //默认情况下类名首字母小写就是表名
        // Mono<User> usersMono = r2dbcEntityTemplate.selectOne(Query.query(Criteria.where("uid").is(id)), User.class);
        return r2dbcEntityTemplate.select(User.class)
                .from("users")
                .matching(Query.query(Criteria.where("uid").is(id)))
                .one();
    }

    @Override
    public void addUser(User user) {
        //默认就是对象的类型就是表名,然后对象中的属性名就是列名
//        r2dbcEntityTemplate.insert(user);
        r2dbcEntityTemplate.insert(User.class).into("users").using(user).subscribe();
    }


    @Override
    public Flux<User> findAllUser() {
        return r2dbcEntityTemplate.select(User.class).from("users").all();
    }

    @Override
    public Flux<User> findByNameLike(String name) {
        return r2dbcEntityTemplate.select(User.class).from("users").matching(Query.query(Criteria.where("name").like("%"+name+"%"))).all();
    }

    @Override
    public Mono<User> findByNameEquals(String name) {
        return r2dbcEntityTemplate.select(User.class).from("users").matching(Query.query(Criteria.where("name").is(name))).one();
    }

    @Override
    public Mono<Integer> deleteByNameEquals(String name) {
        return r2dbcEntityTemplate
                .delete(User.class)
                .from("users")
                .matching(Query.query(Criteria.where("name").is(name)))
                .all();
    }

    @Override
    public void updateUser(User user) {

        r2dbcEntityTemplate.update(User.class)
                .inTable("users")
                .matching(Query.query(Criteria.where("uid").is(user.getUid())))
                .apply(Update.update("age",user.getAge()))
                .subscribe();
    }

    @Override
    public Mono<User> findFirstByNameLike(String name) {
        return r2dbcEntityTemplate.select(User.class).from("users").matching(Query.query(Criteria.where("name").like("%"+name+"%")))
                .first();
    }
}
